import { reqGetCode, reqRegister, reqUserLogin, reqUserInfo, reqLogOut } from "@/api"
import { setToken, getToken, removeToken } from "@/utils/token"
// 登录与注册的仓库
export default {
    actions: {
        // 获取注册验证码
        async getCode({ commit }, phone) {
            let result = await reqGetCode(phone)
            if (result.code == 200) {
                commit("GETCODE", result.data)
                return "ok"
            } else {
                return Promise.reject(new Error(result.message));
            }
        },

        // 注册用户
        async registeredUser({ commit }, user) {
            let result = await reqRegister(user)
            if (result.code == 200) {
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        // 用户登录
        async userLogin({ commit }, data) {
            let result = await reqUserLogin(data)
            if (result.code == 200) {
                // 将用户的token保存到state中
                commit("USERLOGIN", result.data.token)
                // 将token永久保存
                setToken(result.data.token)
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        // 获取用户信息
        async getUserInfo({ commit }) {
            let result = await reqUserInfo()
            if (result.code == 200) {
                commit("GETUSERINFO", result.data)
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        // 退出登录
        async userLogOut({ commit }) {
            let result = await reqLogOut()
            if (result.code == 200) {
                commit("CLEAR")
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        }
    },
    mutations: {
        GETCODE(state, code) {
            state.code = code
        },
        USERLOGIN(state, token) {
            state.token = token
        },
        GETUSERINFO(state, userInfo) {
            state.userInfo = userInfo
        },
        CLEAR(state) {
            state.token = '';
            state.userInfo = '';
            removeToken()
        }
    },
    state: {
        code: '',
        // 用的是永久保存的token
        token: getToken(),
        userInfo: {}
    },
    getters: {}
}